from django import forms
from .models import Server, CDNDomain, RequestUrl, AutoTask, ManualPreheat
from django.contrib.auth.models import User

class ServerForm(forms.ModelForm):
    """服务器表单"""
    class Meta:
        model = Server
        fields = ['ip', 'ssh_port', 'ssh_password', 'remark']
        widgets = {
            'ssh_password': forms.PasswordInput(render_value=True),
        }

class CDNDomainForm(forms.ModelForm):
    """CDN域名表单"""
    class Meta:
        model = CDNDomain
        fields = ['domain', 'vendor', 'project']

class RequestUrlForm(forms.ModelForm):
    """请求地址表单"""
    # 添加批量URL输入字段，默认不显示
    batch_urls = forms.CharField(widget=forms.Textarea(attrs={'rows': 8, 'placeholder': '每行输入一个URL，如：\n/image/logo1.png\n/image/logo2.png'}), required=False)

    def __init__(self, *args, **kwargs):
        # 移除添加模式参数，固定为批量添加
        kwargs.pop('add_mode', None)
        self.add_mode = 'batch_add'  # 固定为批量添加模式
        super().__init__(*args, **kwargs)
        
        # 始终将url字段设置为非必填，因为我们只使用批量添加
        self.fields['url'].required = False

    class Meta:
        model = RequestUrl
        fields = ['url', 'cdn_domain']
        widgets = {
            'url': forms.TextInput(attrs={'placeholder': '/image/logo.png'})
        }

    def clean_batch_urls(self):
        """验证批量URL输入"""
        batch_urls = self.cleaned_data.get('batch_urls', '').strip()
        if batch_urls:
            urls = [url.strip() for url in batch_urls.split('\n') if url.strip()]
            return urls
        return []
    
    def clean(self):
        cleaned_data = super().clean()
        batch_urls = cleaned_data.get('batch_urls')
        
        # 验证批量URL输入不能为空
        if not batch_urls:
            self.add_error('batch_urls', '请至少输入一个URL')
        
        return cleaned_data

class AutoTaskForm(forms.ModelForm):
    """自动任务表单"""
    # 添加用于筛选的CDN域名字段
    cdn_domain_filter = forms.ModelChoiceField(
        queryset=CDNDomain.objects.all(),
        label='按CDN域名筛选',
        required=False,
        empty_label='全部域名'
    )

    def __init__(self, *args, **kwargs):
        # 获取request对象（如果提供）
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)
        
        # 如果有请求对象和cdn_domain参数，过滤请求地址选项
        if self.request and 'cdn_domain' in self.request.GET:
            try:
                cdn_domain_id = int(self.request.GET['cdn_domain'])
                self.fields['cdn_domain_filter'].initial = cdn_domain_id
                # 过滤请求地址选项
                self.fields['request_urls'].queryset = RequestUrl.objects.filter(cdn_domain_id=cdn_domain_id).order_by('url')
            except (ValueError, CDNDomain.DoesNotExist):
                # 无效的域名ID，使用所有请求地址
                pass
        elif self.initial.get('cdn_domain_filter'):
            # 如果表单初始值中有cdn_domain_filter，使用它来过滤请求地址
            try:
                cdn_domain_id = int(self.initial['cdn_domain_filter'])
                self.fields['request_urls'].queryset = RequestUrl.objects.filter(cdn_domain_id=cdn_domain_id).order_by('url')
            except (ValueError, CDNDomain.DoesNotExist):
                pass

    class Meta:
        model = AutoTask
        fields = ['name', 'description', 'servers', 'request_urls', 'task_type', 'interval', 'is_active']
        widgets = {
            'servers': forms.CheckboxSelectMultiple,
            'request_urls': forms.CheckboxSelectMultiple,
        }

class ManualPreheatForm(forms.ModelForm):
    """手动预热表单"""

# 用户管理表单
class UserCreationForm(forms.ModelForm):
    """创建新用户的表单"""
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
    password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    email = forms.EmailField(label='邮箱', required=False)
    phone = forms.CharField(label='手机号', max_length=20, required=False)
    
    class Meta:
        model = User
        fields = ['username', 'email', 'phone']
        
    def clean_password2(self):
        # 检查两次密码输入是否一致
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("两次输入的密码不一致")
        return password2
    
    def save(self, commit=True):
        # 创建用户并设置密码
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        # 保存手机号信息到用户的extra_data中（如果Django版本不支持自定义字段）
        if self.cleaned_data.get('phone'):
            # 在实际项目中，可能需要使用自定义用户模型或用户配置文件模型
            # 这里仅作为示例，实际应用可能需要扩展User模型
            pass
        if commit:
            user.save()
        return user

class UserUpdateForm(forms.ModelForm):
    """更新用户信息的表单"""
    email = forms.EmailField(label='邮箱', required=False)
    phone = forms.CharField(label='手机号', max_length=20, required=False)
    
    class Meta:
        model = User
        fields = ['username', 'email', 'phone']
        
    def save(self, commit=True):
        user = super().save(commit=False)
        # 保存手机号信息到用户的extra_data中（如果Django版本不支持自定义字段）
        if self.cleaned_data.get('phone'):
            # 在实际项目中，可能需要使用自定义用户模型或用户配置文件模型
            pass
        if commit:
            user.save()
        return user

class UserPasswordChangeForm(forms.Form):
    """修改用户密码的表单"""
    current_password = forms.CharField(label='当前密码', widget=forms.PasswordInput)
    new_password1 = forms.CharField(label='新密码', widget=forms.PasswordInput)
    new_password2 = forms.CharField(label='确认新密码', widget=forms.PasswordInput)
    
    def __init__(self, user, *args, **kwargs):
        self.user = user
        # 确保kwargs中不包含user参数，避免传递给父类
        super().__init__(*args, **kwargs)
        
    def clean_current_password(self):
        # 验证当前密码是否正确
        current_password = self.cleaned_data.get("current_password")
        if not self.user or not self.user.check_password(current_password):
            raise forms.ValidationError("当前密码输入错误")
        return current_password
        
    def clean_new_password2(self):
        # 检查两次新密码输入是否一致
        new_password1 = self.cleaned_data.get("new_password1")
        new_password2 = self.cleaned_data.get("new_password2")
        if new_password1 and new_password2 and new_password1 != new_password2:
            raise forms.ValidationError("两次输入的新密码不一致")
        return new_password2
        
    def save(self):
        # 修改用户密码
        new_password = self.cleaned_data.get("new_password1")
        if self.user:
            self.user.set_password(new_password)
            self.user.save()
        return self.user


class ManualPreheatForm(forms.ModelForm):
    """手动预热表单"""
    # 添加任务名称和描述字段
    name = forms.CharField(label='任务名称', max_length=100, required=True)
    description = forms.CharField(label='任务描述', widget=forms.Textarea, required=False)
    
    # 添加用于筛选的CDN域名字段
    cdn_domain_filter = forms.ModelChoiceField(
        queryset=CDNDomain.objects.all(),
        label='按CDN域名筛选',
        required=False,
        empty_label='全部域名'
    )

    def __init__(self, *args, **kwargs):
        # 获取request对象（如果提供）
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)
        
        # 如果有请求对象和cdn_domain参数，过滤请求地址选项
        if self.request and 'cdn_domain' in self.request.GET:
            try:
                cdn_domain_id = int(self.request.GET['cdn_domain'])
                self.fields['cdn_domain_filter'].initial = cdn_domain_id
                # 过滤请求地址选项
                self.fields['request_urls'].queryset = RequestUrl.objects.filter(cdn_domain_id=cdn_domain_id).order_by('url')
            except (ValueError, CDNDomain.DoesNotExist):
                # 无效的域名ID，使用所有请求地址
                pass
        elif self.initial.get('cdn_domain_filter'):
            # 如果表单初始值中有cdn_domain_filter，使用它来过滤请求地址
            try:
                cdn_domain_id = int(self.initial['cdn_domain_filter'])
                self.fields['request_urls'].queryset = RequestUrl.objects.filter(cdn_domain_id=cdn_domain_id).order_by('url')
            except (ValueError, CDNDomain.DoesNotExist):
                pass

    class Meta:
        model = ManualPreheat
        fields = ['name', 'description', 'servers', 'request_urls']
        widgets = {
            'servers': forms.CheckboxSelectMultiple,
            'request_urls': forms.CheckboxSelectMultiple,
        }